<template>
  <div class="customer-info">
    <h1>客户资料管理</h1>
    <div class="table-container">
      <!-- 添加按钮和搜索框 -->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <el-button type="primary" @click="showAddForm">添加客户</el-button>
        <div>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入客户姓名"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="searchCustomers"
            @keyup.enter="searchCustomers"
          />
          <el-button type="primary" @click="searchCustomers">搜索</el-button>
        </div>
      </div>

      <el-table :data="customerList" style="width: 100%" border>
        <el-table-column prop="customerName" label="客户名称" width="150" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="type" label="客户类型" width="150">
          <template #default="scope">
            <el-tag :type="getCustomerTypeTagType(scope.row.type)">
              {{ getCustomerTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
              size="small"
              @click="showEditForm(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteCustomer(scope.row)"
              :disabled="scope.row.deleted === 1">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加客户表单对话框 -->
    <el-dialog title="添加客户" v-model="addFormVisible" width="500px">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="addForm.customerName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>
        <el-form-item label="客户类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择客户类型">
            <el-option label="普通客户" value="0"></el-option>
            <el-option label="企事业客户" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input 
            v-model="addForm.createTime" 
            readonly 
            placeholder="系统自动生成">
          </el-input>
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-input 
            v-model="addForm.updateTime" 
            readonly 
            placeholder="系统自动生成">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑客户表单对话框 -->
    <el-dialog title="编辑客户" v-model="editFormVisible" width="500px">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="editForm.customerName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
        <el-form-item label="客户类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择客户类型">
            <el-option label="普通客户" value="0"></el-option>
            <el-option label="企事业客户" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCustomerInfoAPI, updateCustomerStatusAPI, deleteCustomerAPI, updateCustomerAPI, addCustomerAPI } from '@/apis/user'

export default {
  name: 'CustomerInfo',
  data() {
    return {
      customerList: [], // 当前显示的客户列表（可能经过搜索过滤）
    allCustomerList: [], // 保存所有客户数据
    searchKeyword: '', // 搜索关键词
      // 添加表单相关
      addFormVisible: false,
      addForm: {
        customerName: '',
        phone: '',
        address: '',
        type: '',
        createTime: '',
        updateTime: ''
      },
      addFormRules: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择客户类型', trigger: 'change' }
        ]
      },
      // 编辑表单相关
      editFormVisible: false,
      editForm: {
        id: '',
        customerName: '',
        phone: '',
        address: '',
        type: ''
      },
      editFormRules: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择客户类型', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 显示添加表单
    showAddForm() {
      const now = new Date();
      const timeString = now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0') + ' ' +
        String(now.getHours()).padStart(2, '0') + ':' +
        String(now.getMinutes()).padStart(2, '0') + ':' +
        String(now.getSeconds()).padStart(2, '0');
      
      this.addForm = {
        customerName: '',
        phone: '',
        address: '',
        type: '',
        createTime: timeString,
        updateTime: timeString
      }
      this.addFormVisible = true
    },

    // 取消添加
    cancelAdd() {
      this.addFormVisible = false
      this.$refs.addFormRef.resetFields()
    },

    // 确认添加
    confirmAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 添加创建时间和更新时间
            const now = new Date();
            const timeString = now.getFullYear() + '-' +
              String(now.getMonth() + 1).padStart(2, '0') + '-' +
              String(now.getDate()).padStart(2, '0') + ' ' +
              String(now.getHours()).padStart(2, '0') + ':' +
              String(now.getMinutes()).padStart(2, '0') + ':' +
              String(now.getSeconds()).padStart(2, '0');
            
            const customerData = {
              ...this.addForm,
              createTime: timeString,
              updateTime: timeString,
              // 转换type字段的值，使保存到后端的值与显示一致
              type: this.addForm.type === '0' ? '普通客户' : 
                    this.addForm.type === '1' ? '企事业客户' : 
                    this.addForm.type
            };

            // 调用后端接口添加客户
            await addCustomerAPI(customerData)
            
            // 添加成功后更新列表
            this.$message({
              type: 'success',
              message: '添加客户成功!'
            })

            // 关闭对话框
            this.addFormVisible = false
            
            // 重新获取客户列表
            await this.getAllCustomers()
          } catch (error) {
            console.error('添加客户失败:', error)
            this.$message({
              type: 'error',
              message: '添加客户失败: ' + (error.message || error.msg || '未知错误')
            })
          }
        }
      })
    },
    
    // 显示编辑表单
    showEditForm(row) {
      this.editForm = {
        id: row.id,
        customerName: row.customerName,
        phone: row.phone,
        address: row.address,
        type: row.type
      }
      this.editFormVisible = true
    },

    // 取消编辑
    cancelEdit() {
      this.editFormVisible = false
      this.editForm = {
        id: '',
        customerName: '',
        phone: '',
        address: '',
        type: ''
      }
    },

    // 确认编辑
    confirmEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 处理type字段，确保保存到后端的值与显示一致
            const editData = {
              ...this.editForm,
              type: this.editForm.type === '0' ? '普通客户' : 
                    this.editForm.type === '1' ? '企事业客户' : 
                    this.editForm.type
            };

            // 调用后端接口更新客户信息
            await updateCustomerAPI(editData)

            // 更新成功后更新前端数据
            const index = this.customerList.findIndex(item => item.id === this.editForm.id)
            if (index > -1) {
              this.customerList[index] = { ...this.editForm }
              // 更新时间
              const now = new Date()
              this.customerList[index].updateTime = now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + ' ' +
                String(now.getHours()).padStart(2, '0') + ':' +
                String(now.getMinutes()).padStart(2, '0') + ':' +
                String(now.getSeconds()).padStart(2, '0')
            }
            
            // 同时更新完整客户列表中的数据
            const allIndex = this.allCustomerList.findIndex(item => item.id === this.editForm.id)
            if (allIndex > -1) {
              this.allCustomerList[allIndex] = { ...this.editForm }
              // 更新时间
              const now = new Date()
              this.allCustomerList[allIndex].updateTime = now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + ' ' +
                String(now.getHours()).padStart(2, '0') + ':' +
                String(now.getMinutes()).padStart(2, '0') + ':' +
                String(now.getSeconds()).padStart(2, '0')
            }

            this.$message({
              type: 'success',
              message: '编辑成功!'
            })

            this.cancelEdit()
          } catch (error) {
            console.error('编辑客户失败:', error)
            this.$message({
              type: 'error',
              message: '编辑客户失败: ' + (error.message || error.msg || '未知错误')
            })
          }
        }
      })
    },

    // 获取客户类型标签类型
    getCustomerTypeTagType(type) {
      switch (type) {
        case 'enterprise':
        case 'company':
        case 'business':
        case '1':
          return 'primary'
        case 'individual':
        case 'personal':
        case 'person':
        case '0':
          return 'success'
        default:
          return 'info'
      }
    },

    // 获取客户类型文本
    getCustomerTypeText(type) {
      switch (type) {
        case 'enterprise':
        case 'company':
        case 'business':
        case '1':
          return '企事业客户'
        case 'individual':
        case 'personal':
        case 'person':
        case '0':
          return '普通客户'
        default:
          // 如果type是其他字符串值，直接显示
          return type || '未知类型'
      }
    },

    getStatusType(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'info'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return '禁用'
        case 1:
          return '启用'
        case 2:
          return '删除'
        default:
          return '未知'
      }
    },
    // 切换客户状态
    async toggleStatus(row) {
      try {
        // 准备发送到后端的数据
        const requestData = {
          id: row.id,
          status: row.status === 1 ? 0 : 1 // 切换状态：启用(1) <-> 禁用(0)
        }

        // 调用后端接口更新状态
        await updateCustomerStatusAPI(requestData)

        // 后端更新成功后，再更新前端状态
        row.status = requestData.status

        // 更新时间
        const now = new Date()
        row.updateTime = now.getFullYear() + '-' +
                        String(now.getMonth() + 1).padStart(2, '0') + '-' +
                        String(now.getDate()).padStart(2, '0') + ' ' +
                        String(now.getHours()).padStart(2, '0') + ':' +
                        String(now.getMinutes()).padStart(2, '0') + ':' +
                        String(now.getSeconds()).padStart(2, '0')

        this.$message({
          type: 'success',
          message: `${requestData.status === 1 ? '启用' : '禁用'}成功!`
        })
      } catch (error) {
        console.error('更新客户状态失败:', error)
        this.$message({
          type: 'error',
          message: '更新客户状态失败: ' + (error.message || error.msg || '未知错误')
        })



      }
    },
    // 逻辑删除客户
    deleteCustomer(row) {
      // 删除客户（逻辑删除，将deleted字段设置为1）
      this.$confirm('此操作将删除该客户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用后端接口进行逻辑删除
          await deleteCustomerAPI(row.id)

          // 更新前端数据 - 直接从列表中移除记录
          const index = this.customerList.findIndex(item => item.id === row.id)
          if (index > -1) {
            // 直接从列表中移除记录，而不是标记为已删除
            this.customerList.splice(index, 1)
          }
          
          // 同时从完整客户列表中移除
          const allIndex = this.allCustomerList.findIndex(item => item.id === row.id)
          if (allIndex > -1) {
            this.allCustomerList.splice(allIndex, 1)
          }

          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } catch (error) {
          console.error('删除客户失败:', error)
          this.$message({
            type: 'error',
            message: '删除客户失败: ' + (error.message || error.msg || '未知错误')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 搜索客户
    searchCustomers() {
      if (!this.searchKeyword.trim()) {
        // 如果搜索关键词为空，则显示所有客户
        this.customerList = [...this.allCustomerList];
        return;
      }
      
      // 根据客户姓名过滤客户列表
      this.customerList = this.allCustomerList.filter(customer => 
        customer.customerName && customer.customerName.includes(this.searchKeyword.trim())
      );
    },
    
    // 获取所有客户信息
    async getAllCustomers() {
      try {
        const res = await getCustomerInfoAPI()
        // 确保正确处理返回的数据
        if (res && res.data) {
          // 过滤掉已删除的客户（deleted为1的记录）
          this.allCustomerList = res.data.filter(customer => customer.deleted !== 1)
        } else if (res instanceof Array) {
          // 过滤掉已删除的客户（deleted为1的记录）
          this.allCustomerList = res.filter(customer => customer.deleted !== 1)
        } else {
          this.allCustomerList = []
        }
        
        // 初始化显示所有客户
        this.customerList = [...this.allCustomerList]
      } catch (error) {
        console.error('获取客户信息失败:', error)
        this.$message({
          type: 'error',
          message: '获取客户信息失败: ' + (error.message || error.msg || '未知错误')
        })
        // 发生错误时设置为空数组，避免页面空白
        this.allCustomerList = []
        this.customerList = []
      }
    }
  },
  mounted() {
    // 页面加载时获取所有客户信息
    this.getAllCustomers()
  }
}
</script>

<style scoped>
.customer-info {
  padding: 20px;
  background-color: #f5f5f5;
}

.customer-info h1 {
  margin-top: 0;
}
</style>